<route lang="json5">
{
  style: {
    navigationBarTitleText: '个人资料',
  },
  needLogin: 'true',
}
</route>

<template>
  <view class="profile-info-container">
    <!-- 表单部分 -->
    <view class="profile-card">
      <view class="form-wrapper">
        <wd-form ref="formRef" :model="formData" label-width="160rpx" class="profile-form">
          <!-- 基本信息分组 -->
          <wd-cell-group title="基本信息">
            <!-- 昵称 -->
            <wd-cell title="昵称" required>
              <wd-input
                prop="nickname"
                clearable
                v-model="formData.nickname"
                placeholder="请输入昵称"
                :rules="[{ required: true, message: '请填写昵称' }]"
              />
            </wd-cell>

            <!-- 性别 -->
            <wd-cell title="性别" required>
              <wd-radio-group
                v-model="formData.gender"
                :rules="[{ required: true, message: '请选择性别' }]"
              >
                <wd-radio :value="true">男</wd-radio>
                <wd-radio :value="false">女</wd-radio>
              </wd-radio-group>
            </wd-cell>

            <!-- 地址选择器 -->
            <wd-picker
              :columns="columns"
              label="地址"
              v-model="addressValue"
              :column-change="onChangeDistrict"
              :display-format="displayFormat"
            />

            <!-- 邮箱 -->
            <wd-cell title="邮箱">
              <wd-input
                prop="email"
                clearable
                v-model="formData.email"
                placeholder="请输入邮箱"
                :rules="[{ pattern: emailReg, message: '请输入有效的邮箱地址', required: false }]"
              />
            </wd-cell>
          </wd-cell-group>
        </wd-form>

        <!-- 操作按钮 -->
        <view class="form-actions">
          <wd-button
            type="primary"
            size="large"
            class="submit-btn"
            @click="handleSubmit"
            :loading="submitting"
          >
            保存修改
          </wd-button>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/store'
import { storeToRefs } from 'pinia'
import { toast } from '@/utils/toast'
import { district, codeToNameMap, findAddressCodes } from '@/utils/area'

// 表单引用
const formRef = ref()
const submitting = ref(false)

// 用户信息
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

// 表单数据
const formData = ref({
  id: userInfo.value.id,
  nickname: userInfo.value.nickname,
  gender: userInfo.value.gender,
  province: userInfo.value.province,
  provinceCode: '',
  city: userInfo.value.city,
  cityCode: '',
  country: userInfo.value.country,
  countryCode: '',
  email: userInfo.value.email,
})

// 页面初次加载
onLoad(() => {
  usePageAuth()
})

// 页面挂载时确保用户信息加载
onMounted(async () => {
  // console.log('当前用户ID为：', uni.getStorageSync('userInfo').id)
  const u = await userStore.getUserInfo(uni.getStorageSync('userInfo').id)
  // console.log(u)
  // 设置地址字段
  const addressInfo = {
    province: u.province || '',
    city: u.city || '',
    country: u.country || '',
  }

  // 更新表单数据
  formData.value = {
    ...formData.value,
    ...addressInfo,
    ...findAddressCodes(addressInfo.province, addressInfo.city, addressInfo.country),
  }

  // 设置地址选择器值
  addressValue.value = [
    formData.value.provinceCode || district['0'][0]?.value || '',
    formData.value.cityCode || district[formData.value.provinceCode]?.[0]?.value || '',
    formData.value.countryCode || district[formData.value.cityCode]?.[0]?.value || '',
  ]

  if (!addressValue.value[0] && district['0']?.length) {
    addressValue.value[0] = district['0'][0].value
  }

  // 更新地区列数据
  updateColumns()
})

// 更新地区列数据
const updateColumns = (val = addressValue.value) => {
  // 省级数据总是存在
  const provinceList = district['0'] || []

  // 根据省级获取市级（如果不存在则取第一个省的数据）
  const cityList = district[val[0]] || (district[0]?.length ? district[district[0][0].value] : [])

  // 根据市级获取县级
  const countryList = district[val[1]] || (cityList.length ? district[cityList[0].value] : [])

  columns.value = [provinceList, cityList, countryList]
}

// 邮箱正则验证
const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

const addressValue = ref(['', '', '']) // 初始化为空值
const columns = ref([]) // 地区列数据

// 区域选择变化处理
const onChangeDistrict = (pickerView, value, columnIndex, resolve) => {
  const item = value[columnIndex]
  if (columnIndex === 0) {
    pickerView.setColumnData(1, district[item.value] || [])
    pickerView.setColumnData(2, district[district[item.value]?.[0]?.value] || [])
  } else if (columnIndex === 1) {
    pickerView.setColumnData(2, district[item.value] || [])
  }
  resolve()
}

// 显示格式化
const displayFormat = (items) => {
  return items.map((item) => item.label).join('-')
}

// 监听选择器变化，同步到表单数据
watch(
  addressValue,
  (newVal) => {
    updateColumns(newVal) // 更新列数据

    const [provinceCode, cityCode, countryCode] = newVal

    formData.value.provinceCode = provinceCode
    formData.value.province = codeToNameMap[provinceCode] || ''

    formData.value.cityCode = cityCode
    formData.value.city = codeToNameMap[cityCode] || ''

    formData.value.countryCode = countryCode
    formData.value.country = codeToNameMap[countryCode] || ''
  },
  { deep: true },
)

// 提交表单
const handleSubmit = async () => {
  // 表单验证
  const valid = await formRef.value.validate()
  if (!valid) return

  // 验证是否选择了完整的三级地址
  if (!formData.value.province || !formData.value.city || !formData.value.country) {
    toast.warning('请选择完整的省市区')
    return
  }

  submitting.value = true
  try {
    // console.log(formData.value)
    const res = await userStore.updateUser(formData.value)
  } catch (error) {
    console.error('更新用户信息失败:', error)
    toast.error('更新失败，请稍后再试')
  } finally {
    submitting.value = false
  }
}
</script>

<style lang="scss" scoped>
.profile-info-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #f5f9ff 0%, #ffffff 60%);
  padding: 32rpx;
}

.profile-card {
  background-color: #ffffff;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
  padding: 40rpx 32rpx;
}

::v-deep .wd-cell-group__title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  padding: 24rpx 0 20rpx;
}

::v-deep .wd-cell {
  padding: 28rpx 0;
}

.form-actions {
  margin-top: 60rpx;
  padding: 0 20rpx;
}

.submit-btn {
  height: 88rpx;
  border-radius: 48rpx;
  font-size: 32rpx;
  font-weight: 500;
  background: linear-gradient(135deg, #3366ff, #6495ed);
  transition: all 0.2s ease;

  &::after {
    display: none;
  }

  &:active {
    transform: scale(0.98);
  }
}
</style>
